package com.yuke.cloud.service.omc.controller.frontend;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.base.dto.MsgNotificationBody;
import com.yuke.cloud.common.core.mq.RabbitSender;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.opc.service.OpcSendNotifyFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.omc.config.Iputil;
import com.yuke.cloud.service.omc.config.Unifiedorder;
import com.yuke.cloud.service.omc.config.wxconfig;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.entity.OdsPayOrder;
import com.yuke.cloud.service.omc.payUtil.GetRSA;
import com.yuke.cloud.service.omc.payUtil.Getbanknameutil;
import com.yuke.cloud.service.omc.payUtil.MD5Util;
import com.yuke.cloud.service.omc.payUtil.payutil;
import com.yuke.cloud.service.omc.service.OdsOrderService;
import com.yuke.cloud.service.omc.service.OdsPayOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.yuke.cloud.service.omc.payUtil.payutil.updateit;

/**
 * Created by ssx on 2018/09/03.
 */
@Api(value = "WEB - OdsOrderController", tags = "处理OdsOrder相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/wxpay")
@Slf4j
public class WxPayController extends BaseController {
    private Logger logger = Logger.getLogger(WxPayController.class);
    private static final String QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
    private static final String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    @Resource
    private OdsOrderService odsOrderService;

    @Resource
    private OdsPayOrderService odsPayOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmcFeignApi smcFeignApi;

    @Autowired
    private CmcFeignApi cmcFeignApi;

    @Autowired
    private OpcSendNotifyFeignApi opcSendNotifyFeignApi;

    @Autowired
    private RabbitSender rabbitSender;


    //微信预支付
    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新")
    public Wrapper add(@RequestBody JSONObject json) throws Exception {
        TreeMap<String, Object> treeMap = new TreeMap<>();
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        //先测试这个获取ip的方法，不行的话再测试iptuil.getipaddress;
        String billrcreatip = Iputil.getLocalIpAddr(); // request.getRemoteAddr();

        // add by wg 20190328 如果订单重新提交，则只更新订单表，不用新生成订单
        Long getsnowid = null;
        OdsPayOrder payOrder = new OdsPayOrder();
        payOrder.setOrderIds(json.get("pay_order_ids").toString());
        List<OdsPayOrder> listPayOrder = odsPayOrderService.select(payOrder);
        if (listPayOrder != null && listPayOrder.size() > 0) {
            getsnowid = listPayOrder.get(0).getPayId();
        }

        //用雪花算法生成分布式id
        if (getsnowid == null) {
            getsnowid = odsOrderService.getsnowid();
        }

        map.put("appid", wxconfig.WX_APPID);
        map.put("attach", json.get("paytype").toString());
        map.put("body", "裕客网-商品交易支付");
//        map.put("detail", "null");
        map.put("mch_id", wxconfig.WX_MCHID);
        map.put("notify_url", wxconfig.WX_NOTIFYURL);
        map.put("nonce_str", nonce_str);
        map.put("out_trade_no", getsnowid.toString());
        map.put("sign_type", "MD5");
        map.put("spbill_create_ip", billrcreatip);
//        map.put("time_expire", "null");
//        map.put("time_start", "null");
        map.put("total_fee", Integer.valueOf(json.get("totalpay").toString()));
        map.put("trade_type", wxconfig.WX_TRADETYPE);
        String sign = payutil.createSign("UTF-8", map, wxconfig.WX_SECURITY);
        map.put("sign", sign);
        //map转xml
        Unifiedorder unifiedorder = new Unifiedorder();
        unifiedorder.setAppid(wxconfig.WX_APPID);
        //商户号
        unifiedorder.setMch_id(wxconfig.WX_MCHID);
        unifiedorder.setNonce_str(nonce_str);
        unifiedorder.setBody("裕客网-商品交易支付");
//        unifiedorder.setDetail("null");
        //附加数据可以不加
        unifiedorder.setAttach(json.get("paytype").toString());
        //订单号
        unifiedorder.setOut_trade_no(getsnowid.toString());
//        unifiedorder.setTime_expire("null");
//        unifiedorder.setTime_start("null");
        unifiedorder.setTotal_fee(Integer.valueOf(json.get("totalpay").toString()));
        unifiedorder.setSpbill_create_ip(billrcreatip);
        unifiedorder.setNotify_url(wxconfig.WX_NOTIFYURL);
        unifiedorder.setTrade_type(wxconfig.WX_TRADETYPE);
        unifiedorder.setSign(sign);
        String toXml = payutil.xmlInfo(unifiedorder);

//        String paramXml = new String(toXml.getBytes(), "ISO8859-1");

        String back = payutil.httpsRequest(UNIFIEDORDER_URL, "POST", toXml);// toXml);
        Map restmap = payutil.xmlToMap(back);
        SortedMap<Object, Object> payMap = new TreeMap<Object, Object>();
        if (!restmap.isEmpty() && restmap.get("return_code").equals("SUCCESS")) {
            payMap.put("appid", restmap.get("appid"));
            payMap.put("partnerid", restmap.get("mch_id"));
            payMap.put("prepayid", restmap.get("prepay_id"));
            payMap.put("package", "Sign=WXPay");
            payMap.put("noncestr", restmap.get("nonce_str"));
            payMap.put("timestamp", payTimestamp());
            //二次生成签名
            payMap.put("sign", payutil.createSign("UTF-8", payMap, wxconfig.WX_SECURITY));

            //同时生成支付表，支付表关联包含的订单ids
            OdsPayOrder odsPayOrder = new OdsPayOrder();
            //out_trade_no就是payorder的id；
            odsPayOrder.setPayId(getsnowid);
            odsPayOrder.setOrderIds(json.get("pay_order_ids").toString());

            if (listPayOrder != null && listPayOrder.size() > 0) {
                odsPayOrderService.update(odsPayOrder);
            } else {
                // 如果已经存在过订单集合，则重新支付时是每个订单单独支付，此时应删除掉原有的订单集合
                odsPayOrderService.deleteByOrderIds(json.get("pay_order_ids").toString());

                odsPayOrderService.save(odsPayOrder);
            }

            return WrapMapper.ok(maptojson(payMap));
        }
        return WrapMapper.error("预支付失败");
    }

    //微信返回
    @RequestMapping(value = "/notifyWeiXinPay", produces = MediaType.APPLICATION_JSON_VALUE)
// @RequestDescription("支付回调地址")
    @ResponseBody
    public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = payutil.xmlToMap(resultxml);
        outSteam.close();
        inStream.close();
        Map<String, String> return_data = new HashMap<String, String>();
        if (!isTenpaySign(params)) {
            // 支付失败
            return_data.put("return_code", "FAIL");
            return_data.put("return_msg", "return_code不正确");
            return payutil.toXml(return_data);
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // ------------------------------
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            // ------------------------------
            String total_fee = params.get("total_fee");
//            double v = Double.valueOf(total_fee) / 100;
            String out_trade_no = String.valueOf(Long.parseLong(params.get("out_trade_no").split("O")[0]));
            SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddHHmmss");
            Date accountTime = sim.parse(params.get("time_end"));
            SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String ordertime = sim1.format(new Date());
            String totalAmount = total_fee;
            String appId = params.get("appid");
            String tradeNo = params.get("transaction_id");
            //支付成功以后修改订单装填，处理逻辑等等
            return_data.put("return_code", "SUCCESS");
            return_data.put("return_msg", "OK");

            // todo 付款成功后的业务逻辑处理...可与支付宝的逻辑一起整理到service层
            OdsPayOrder ods = odsPayOrderService.findById(Long.valueOf(params.get("out_trade_no")));
            String total_amount = params.get("total_fee");  // 微信支付接口返回总付款，单位分
            String orderIds = ods.getOrderIds();
            String[] split = orderIds.split(",");

            StringBuilder sb = new StringBuilder();
            // mod by wg 20190516
//                    OdsOrder byId1 = odsOrderService.findById(Long.valueOf(split[0]));
//                    Byte orderType = byId1.getOrderType();
//                    if (orderType.toString().substring(0, 1).equals("1")) {  // 消费者购买订单

            ods.setAmountPaid(Integer.valueOf(total_amount));
            odsPayOrderService.update(ods);

            if (params.get("attach").equals("normal")) {
                List<Map> list = new ArrayList<>();
                List<Long> shopIds = new ArrayList<>(); // add by wg 20190516 保存店铺信息
                List<OdsOrder> odsOrders = new ArrayList<>(); // add by wg 20190516 保存订单信息
                for (int i = 0; i < split.length; i++) {
                    OdsOrder byId2 = odsOrderService.findById(Long.valueOf(split[i]));


                    //todo 第一删除redis里面的key，第二修改订单的状态
                    OdsOrder odsOrder = new OdsOrder();
                    odsOrder.setOrderId(Long.valueOf(split[i]));
                    odsOrder.setPayStatus((byte) 1);
                    odsOrder.setPayType((byte)3);  // add by wg 20190711
                    odsOrder.setPayTime(new Date());

                    // add by wg 20190711 增加货到付款处理
                    if (byId2.getPayType().equals((byte) 0)) {  // 货到付款
                        odsOrder.setShippingStatus((byte) 3);
                        odsOrder.setOrderStatus((byte) 2);
                    } else {
                        //odsOrder.setShippingStatus((byte) 0); //zyq20210203
                        odsOrder.setOrderStatus((byte) 1);
                    }

                    if (byId2 != null) {
                        odsOrder.setAmountPaid(byId2.getAmountPayable());
                    } else {
                        odsOrder.setAmountPaid(Integer.valueOf(total_amount));
                    }

                    //保存到数据库，修改订单状态为已付款，未发货
                    // todo 目前对于返利结算直接在订单中优惠，因此此时直接将是否返利字段置为true，20190727
                    if (byId2 != null && byId2.getOrderType() == 2) {
                        odsOrder.setIsCheckout(true);
                    }

                    odsOrderService.update(odsOrder);

                    //如果此单使用了优惠券，标记使用状态
                    if (null != byId2 && null != byId2.getCouponReceiveId()
                            &&  null != byId2.getCouponMoney()){
                        System.out.println("如果此单使用了优惠券，标记使用状态");
                        cmcFeignApi.updateCouponReceive(Long.valueOf(byId2.getCouponReceiveId()),Long.valueOf(split[i]));
                    }

                    // add by wg 20190711 增加货到付款处理
                    if (byId2.getPayType() != 0) {
                        // mod by wg 20190727
                        if (byId2.getOrderType() == 1) {
                            redisTemplate.delete("zero:" + split[i]);
                        } else {
                            redisTemplate.delete("first:" + split[i]);
                        }

                    }
                    // add by wg 20190711 增加货到付款处理
                    if (byId2.getPayType() != 0) {
                        String a = String.valueOf(byId2.getShopId());
                        if (i == split.length - 1) {
                            sb.append(a);
                        } else {
                            sb.append(a + ",");
                        }

                        shopIds.add(byId2.getShopId());
                        if (byId2.getIsFactory()) {
                            shopIds.add(byId2.getFactoryShopId());
                        }
                        odsOrders.add(byId2);
                    }
                }

                // add by wg 20190711 增加货到付款处理
                if (odsOrders.size() > 0) {
                    // mod by wg 20190516 V1.1版，如果配送类型是同城发送时，直接通知仓库发货，或者配送类型是仓库配送的即时达类型也由仓库发货
                    // 获取店铺信息
                    List<ShopInfoDto> shopInfoDtos = smcFeignApi.getShopInfoByShopIds(shopIds);
                    for (OdsOrder odsOrder : odsOrders) {
                        if (odsOrder.getShippingType() == 0) {  // 同城即时达
                            for (ShopInfoDto shopInfoDto : shopInfoDtos) {
                                if (odsOrder.getShopId().equals(shopInfoDto.getShopId()) && shopInfoDto.getShopType() == 1) {  // 店铺类型为云顶店铺
                                    MsgNotificationBody msg = new MsgNotificationBody();
                                    msg.setTitle("订单处理");
                                    msg.setContent("您的店铺有订单需要处理");
                                    msg.setTime(new Date());
                                    msg.setReceiveType((byte) 3);
                                    msg.setOrderType((byte) 1);
                                    msg.setMsgType("orderMsg");
                                    Long userId = shopInfoDto.getUserId();
                                    opcSendNotifyFeignApi.sendnotify(userId.toString(), "订单处理", "您的店铺有订单需要处理", 0);
                                    opcSendNotifyFeignApi.sendnotify(userId.toString(), "订单处理", JSON.toJSONString(msg), 1);

                                    break;
                                } else if (odsOrder.getShopId().equals(shopInfoDto.getShopId()) && shopInfoDto.getShopType() == 4) {  // 直营店铺
                                    //同时通知仓库(用rabbitmq发送)，有新订单需要打印
                                    //同时通知仓库(用rabbitmq发送)，有新订单需要打印
                                    odsPayOrderService.sendMsgToWarehouse(odsOrder.getShopId().toString(), null);
                                }
                            }
                        } else if (odsOrder.getIsFactory()) {  // 厂家直销订单，直接通知厂家发货
                            for (ShopInfoDto shopInfoDto : shopInfoDtos) {
                                if (odsOrder.getFactoryShopId().equals(shopInfoDto.getShopId()) && shopInfoDto.getShopType() == 3) {  // 店铺类型为云顶店铺
                                    MsgNotificationBody msg = new MsgNotificationBody();
                                    msg.setTitle("订单处理");
                                    msg.setContent("您有订单需要发货");
                                    msg.setTime(new Date());
                                    msg.setReceiveType((byte) 3);
                                    msg.setOrderType((byte) 1);
                                    msg.setMsgType("orderMsg");
                                    Long userId = shopInfoDto.getUserId();
                                    opcSendNotifyFeignApi.sendnotify(userId.toString(), "订单处理", "您有订单需要发货", 0);
                                    opcSendNotifyFeignApi.sendnotify(userId.toString(), "订单处理", JSON.toJSONString(msg), 1);

                                    break;
                                }
                            }
                        } else if (odsOrder.getShippingType() == 2) { // 同城快送
                            //同时通知仓库(用rabbitmq发送)，有新订单需要打印
                            odsPayOrderService.sendMsgToWarehouse(odsOrder.getShopId().toString(), null);
                        } else if (odsOrder.getWarehouseId() != null){  // add by wg 20190717
                            odsPayOrderService.sendMsgToWarehouse(null, odsOrder.getWarehouseId().toString());
                        }
                    }
                }
                // mod by wg 20190516
//                    } else if (orderType.toString().substring(0, 1).equals("2")) {
            }

            return payutil.toXml(return_data);
        }
    }



    public static boolean isTenpaySign(Map<String, String> map) {
        String characterEncoding = "utf-8";
        String charset = "utf-8";
        String signFromAPIResponse = map.get("sign");
        if (signFromAPIResponse == null || signFromAPIResponse.equals("")) {
            System.out.println("API返回的数据签名数据不存在，有可能被第三方篡改!!!");
            return false;
        }
        System.out.println("服务器回包里面的签名是:" + signFromAPIResponse);
        //过滤空 设置 TreeMap
        SortedMap<String, String> packageParams = new TreeMap();

        for (String parameter : map.keySet()) {
            String parameterValue = map.get(parameter);
            String v = "";
            if (null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }

        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();

        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }

        sb.append("key=" + wxconfig.WX_SECURITY);

        //将API返回的数据根据用签名算法进行计算新的签名，用来跟API返回的签名进行比较
        //算出签名
        String resultSign = "";
        String tobesign = sb.toString();

        if (null == charset || "".equals(charset)) {
            resultSign = MD5Util.MD5Encode(tobesign, characterEncoding).toUpperCase();
        } else {
            try {
                resultSign = MD5Util.MD5Encode(tobesign, characterEncoding).toUpperCase();
            } catch (Exception e) {
                resultSign = MD5Util.MD5Encode(tobesign, characterEncoding).toUpperCase();
            }
        }

        String tenpaySign = ((String) packageParams.get("sign")).toUpperCase();
        return tenpaySign.equals(resultSign);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        return WrapMapper.ok();
    }


    /**
     * 微信支付订单查询
     *
     * @param transaction_id 微信订单号
     * @param out_trade_no   平台订单号
     * @return
     */
    @RequestMapping(value = "/querypay", method = RequestMethod.POST)
    @ResponseBody
    public Wrapper weixin_pay_query(@PathVariable("transaction_id") String transaction_id, @PathVariable("out_trade_no") String out_trade_no) {
        logger.info("infoMsg:--- 微信支付订单查询开始");
        // Response resp = this.getReponse();
        String message = "";
        Map return_map = null;
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);

        SortedMap<Object, Object> req_map = new TreeMap<Object, Object>();
        req_map.put("appid", wxconfig.WX_APPID);
        req_map.put("mch_id", wxconfig.WX_MCHID);
        if (!transaction_id.trim().equals(null) && transaction_id.trim() != "") {
            req_map.put("transaction_id", transaction_id);
        }
        req_map.put("out_trade_no", out_trade_no);
        req_map.put("nonce_str", nonce_str);
        String sign2 = payutil.createSign("UTF-8", req_map, wxconfig.WX_SECURITY);
        Map<String, String> mmap = new HashMap<String, String>();

        //map转xml
        mmap.put("appid", wxconfig.WX_APPID);
        mmap.put("mch_id", wxconfig.WX_MCHID);
        if (!transaction_id.trim().equals(null) && transaction_id.trim() != "") {
            mmap.put("transaction_id", transaction_id);
        }
        mmap.put("out_trade_no", out_trade_no);
        mmap.put("nonce_str", nonce_str);
        mmap.put("sign", sign2);
        String toXml = payutil.toXml(mmap);
        String back = payutil.httpsRequest(UNIFIEDORDER_URL, "POST", toXml);
        Map map = null;
        try {
            map = payutil.xmlToMap(back);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!map.isEmpty()) {
            String return_code = map.get("return_code").toString();
            if (return_code.equals("SUCCESS")) {
                String result_code = map.get("return_code").toString();
                if (result_code.equals("SUCCESS")) {
                    message = (String) req_map.get("trade_state_desc");
                    return WrapMapper.ok(message);
                }
            } else {
                message = (String) req_map.get("err_code_des");
                return WrapMapper.ok(message);
            }

            return WrapMapper.error();
        }
        return WrapMapper.error("查询出错");
    }


    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "odsOrder", value = "需要修改的内容") @RequestBody OdsOrder odsOrder) {
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<OdsOrder> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        return WrapMapper.ok();
    }

    public static String payTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public static JSONObject maptojson(Map map) {
        JSONObject json = new JSONObject();
        for (Object key : map.keySet()) {
            json.put((String) key, map.get(key));
        }
        return json;
    }

    @PostMapping("/refund")
    @ApiOperation(httpMethod = "POST", value = "微信退款")
    //微信退款需要多个参数，请求参数xml格式（包括加密），请求的url，证书文件目录，证书密码
    public int payback(JSONObject jsonObject) {

        SortedMap<Object, Object> params = new TreeMap<Object, Object>();
        params.put("appid", wxconfig.WX_APPID);
        params.put("mch_id", wxconfig.WX_MCHID);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        params.put("nonce_str", nonce_str);
        //如果有微信订单号，和商户订单号，有限微信订单号,判断有没有微信订单号
//        if (true) {
//            params.put("transaction", "");
//        } else {
//            params.put("out_trade_no", "");
//        }
        params.put("out_trade_no", jsonObject.get("out_trade_no").toString());

        //退款单号，uuid生成，保存数据库还是怎么处理
        params.put("out_refund_no", jsonObject.get("out_refund_no").toString());
        //总金额
        params.put("total_fee", jsonObject.get("total_fee").toString());
        params.put("refund_fee", jsonObject.get("refund_amount").toString());
        String sign = payutil.createSign("utf-8", params, wxconfig.WX_SECURITY);
        params.put("sign", sign);
        String requestXml = payutil.getRequestXml(params);
        //证书密码
        try {
            String s = payutil.postSSL(wxconfig.REFUND, requestXml, wxconfig.backpath, wxconfig.certpass);
            Map map = payutil.xmlToMap(s);
            String return_code = map.get("return_code").toString();
            if (return_code.equalsIgnoreCase("SUCCESS")) {
                Object result_code = map.get("result_code");
                if (result_code.equals("SUCCESS")) {
//                    return WrapMapper.ok("微信退款成功，退款金额" + map.get("refund_fee") + "(分)");
                    log.info("微信退款成功，退款金额" + map.get("refund_fee") + "(分)");
                    return 1;
                } else {
//                    return WrapMapper.error("微信退款失败");
                    log.error(map.toString());
                    log.error("微信退款失败");
                    return 0;
                }
            } else {
//                return WrapMapper.error("微信退款请求失败");
                log.error("微信退款请求失败");
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信退款异常：{}", e.getMessage());
            return -1;
        }

    }

    //springboot异步执行
    @Async
    public Map wxtransfer(Map<String, Object> map) throws Exception {
        //商户转账订单号
        //付款单号,雪花算法生成
        String getsnowid = odsOrderService.getsnowid() + "";
        //需要加密
        String account_no = map.get("account_no").toString();
        String getbankname = Getbanknameutil.getbankname(account_no);
        String account_name = map.get("account_name").toString();
        String amount = map.get("money").toString();
        //生成随机字符串
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        //付款说明
        String desc = "日常结算";
        //对银行卡密码和用户名进行rsa算法加密
        String rsa_name = GetRSA.getRSA(account_name, wxconfig.publickey);
        String rsa_no = GetRSA.getRSA(account_no, wxconfig.publickey);
        SortedMap<Object, Object> map1 = new TreeMap<Object, Object>();
        map1.put("mch_id", wxconfig.WX_MCHID);
        map1.put("partner_trade_no", getsnowid);
        map1.put("nonce_str", nonce_str);
        map1.put("enc_bank_no", rsa_no);
        map1.put("bank_code", getbankname);
        map1.put("enc_true_name", rsa_name);
        map1.put("amount", amount);
        map1.put("desc", "裕客网商品收货七天日结算");
        String sign = payutil.createSign("utf_8", map1, wxconfig.WX_SECURITY);
        map1.put("sign", sign);
        String requestXml = payutil.getRequestXml(map1);
        String s = payutil.postSSL(wxconfig.transfer, requestXml, wxconfig.backpath, wxconfig.certpass);
        Map mapback = payutil.xmlToMap(s);
        if (mapback.get("return_code").toString().equals("SUCCESS")) {
            if (mapback.get("result_code").toString().equals("SUCCESS")) {
                logger.info("支付成功,开始修改订单状态");
                List<OdsOrder> all_order_id = updateit(map.get("all_order_id").toString());
                odsOrderService.batchupdate(all_order_id);
            } else {
                logger.info("发送支付请求成功，支付失败");
                Map returnmap = new HashMap();
                returnmap.put("result", "FAIL");
                returnmap.put("Shop_id", map.get("shop_id").toString());
                returnmap.put("all_order_id", map.get("all_order_id"));
                returnmap.put("partner_trade_no", getsnowid);
                return returnmap;
            }
        } else {
            logger.info("发送支付请求失败");
            Map returnmap = new HashMap();
            returnmap.put("result", "FAIL");
            returnmap.put("Shop_id", map.get("shop_id").toString());
            returnmap.put("all_order_id", map.get("all_order_id"));
            returnmap.put("partner_trade_no", getsnowid);
            return returnmap;
        }
        return null;
    }




    public Map querytransfer(Map<String, String> map) throws Exception {
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        SortedMap<Object, Object> map1 = new TreeMap<Object, Object>();
        map1.put("mch_id", wxconfig.WX_MCHID);
        map1.put("partner_trade_no", map.get("partner_trade_no"));
        map1.put("nonce_str", nonce_str);
        String sign = payutil.createSign("utf-8", map1, wxconfig.WX_SECURITY);
        map1.put("sign", sign);
        String requestXml = payutil.getRequestXml(map1);
        String s = payutil.postSSL(wxconfig.transfer, requestXml, wxconfig.backpath, wxconfig.certpass);
        Map mapback = payutil.xmlToMap(s);
        if (mapback.get("return_code").toString().equals("SUCCESS")) {
            if (mapback.get("result_code").toString().equals("SUCCESS")) {
                logger.info("查询结果-转账成功");
                //修改订单状态
                List<OdsOrder> all_order_id = updateit(map.get("all_order_id").toString());
                for (int i = 0; i < all_order_id.size(); i++) {
                    OdsOrder odsOrder1 = all_order_id.get(i);
                    odsOrder1.setIsCheckout(true);
                    odsOrderService.update(odsOrder1);
                }

            }
        }
        return null;
    }


    /*@PostMapping("/tes")
    @ApiOperation(httpMethod = "POST", value = "测试专用")*/
    @Async
    public Wrapper test(Map<String,String>map) {

        return null;
    }


}
